package com.ybwh.springboot2.common.fastjson.mask;

import com.alibaba.fastjson.serializer.BeanContext;
import com.alibaba.fastjson.serializer.ContextValueFilter;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;


/**
 * 字段打码（注解改字段值）
 */
@Slf4j
public class MaskFieldContextValueFilter implements ContextValueFilter {


    @Override
    public Object process(BeanContext context, Object object, String name, Object value) {
        if (value == null || !(value instanceof String)) {
            return value;
        }


        MaskField maskField = context.getAnnation(MaskField.class);
        if (maskField == null) {
            return value;
        }


        if (null == value) {
            return value;
        }

        String s = value.toString();
        if (Objects.equals(s, "")) {
            return value;
        }

        int bi = maskField.beginIndex();
        int ei = maskField.endIndex();
        char mc = maskField.maskChar();

        if (bi < 0) {
            bi = 0;
        }

        int len = s.length();
        if (ei > len) {
            ei = len;
        }

        if (bi > len - 1 || bi >= ei) {
            return value;
        }


        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            if (i >= bi && i < ei) {
                sb.append(mc);
            } else {
                sb.append(s.charAt(i));
            }
        }


        return sb.toString();

    }

}